<template>
  <div class="minapplets">
    <div class="outmain ba_f formwidth">
      <div class="shuju_title mar_b20">
        <div class="shuju_title_text">
          <span>商户端设置</span>
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础设置" name="1">
          <el-form ref="form" :model="form" :rules="rules" label-width="180px" class="mar_t20">
            <el-form-item label="小程序名称" prop="miniName" :required="true">
              <el-input v-model="form.miniName" placeholder="请输入小程序名称"></el-input>
            </el-form-item>
            <el-form-item label="AppID(小程序ID)" prop="miniAppId" :required="true">
              <el-input v-model="form.miniAppId" placeholder="请输入小程序AppID"></el-input>
              <div class="yb_margin lh16">获取方式：微信公众平台-开发-开发设置-开发者ID-小程序AppID</div>
            </el-form-item>
            <el-form-item label="AppSecret(小程序密钥)" prop="miniSecret" :required="true">
              <el-input v-model="form.miniSecret" placeholder="请输入小程序AppSecret" :type="passw">
                <i slot="suffix" :class="icon" @click="showPass"></i>
              </el-input>
              <div class="yb_margin lh16">获取方式：微信公众平台-开发-开发设置-开发者ID-小程序AppSecret</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="用户列表" name="2">
          <div class="pad_20">
            <el-table ref="multipleTable" :data="list" tooltip-effect="dark"
                      style="width: 100%" class="tablecenter">
              <el-table-column label="ID" prop="memberId" width='80'></el-table-column>
              <el-table-column prop="userName" label="用户信息">
                <template slot-scope="scope">
                  <div class="flex pad_tb_10 flex-center">
                    <div class=""><img class="namelogo" :src="scope.row.portrait"/>
                    </div>
                    <div class="flex-col mar_l20 t_c">
                      <div class="overflowlnr">{{scope.row.memberName}}</div>
                      <div class="fon_12 color_9">注册时间：{{scope.row.createdAt}}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="end_time" label="关联平台">
                <template slot-scope="scope">
                  <div class="flex-center" v-if="scope.row.apply_name">{{scope.row.apply_name}}<span v-if="scope.row.applyId">（平台ID：{{scope.row.applyId}}）</span></div>
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="关联门店"
                               show-overflow-tooltip>
                <template slot-scope="scope">
                  <div class="flex-center">
                    <div v-if="scope.row.name">{{scope.row.name}}<span v-if="scope.row.storeId">（门店ID：{{scope.row.storeId}}）</span></div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="关联账号" prop="image" align="left">
                <template slot-scope="scope">
                  <div class="flex pad_tb_10 flex-center">
                    <div class="flex-col mar_l20 t_c">
                      <div class="overflowlnr">{{scope.row.userName}}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next" :total="page.total" :page-size="page.size" :current-page.sync="page.currentPage" @current-change="handleCurrentChange"></el-pagination>
          </div>
        </el-tab-pane>
<!--        <el-tab-pane label="小程序下载" name="3">-->
<!--          <div class="ba_f">-->
<!--            <div class="pad_20">-->
<!--              <el-form ref="form2" :model="form2" label-width="180px" class="">-->
<!--                <div class="stepsLeft mar_t20">-->
<!--                  <el-steps direction="vertical" :active="3">-->
<!--                    <el-step title="下载并安装微信小程序开发者工具，如果已经安装可跳过这一步。">-->
<!--                      <template slot="description">-->
<!--                        <div class="xiazai">-->
<!--                          <a href="https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html" target="_blank">-->
<!--                            <el-button type="primary" class>下载微信开发者工具</el-button>-->
<!--                          </a>-->
<!--                        </div>-->
<!--                      </template>-->
<!--                    </el-step>-->
<!--                    <el-step title="下载小程序代码包，并解压。">-->
<!--                      <template slot="description">-->
<!--                        <div class="xiazai">-->
<!--                          <a :href="downloadPage()" download="小程序代码包">-->
<!--                            <el-button type="primary">下载小程序代码包</el-button>-->
<!--                          </a>-->
<!--                        </div>-->
<!--                      </template>-->
<!--                    </el-step>-->
<!--                    <el-step title="运行微信小程序开发者工具，选择打开项目，打开解压出来的小程序代码包，点击上传。"></el-step>-->
<!--                  </el-steps>-->
<!--                </div>-->
<!--              </el-form>-->
<!--            </div>-->
<!--          </div>-->
<!--        </el-tab-pane>-->
        <el-tab-pane label="上传小程序" name="4">
          <el-form ref="form3" :model="form3" label-width="180px" class="mar_t20" v-show="shawCode=='1'">
            <el-form-item label="版本号">
              <el-input v-model="form3.version" placeholder="请输入版本号" :required="true"></el-input>
            </el-form-item>
            <el-form-item label="版本描述" prop="name">
              <el-input v-model="form3.describe" placeholder="请输入版本描述" :required="true" type="textarea" rows="6"></el-input>
            </el-form-item>
<!--            <el-form-item label="插件选择">-->
<!--              <el-checkbox-group v-model="plugin">-->
<!--                <el-checkbox label="live">小程序直播</el-checkbox>-->
<!--              </el-checkbox-group>-->
<!--              <div class="yb_margin lh16">如当前小程序未开通直播功能请勿勾选</div>-->
<!--            </el-form-item>-->
          </el-form>
          <div class="shawCode t_c pad_30" v-show="shawCode=='2'">
            <img v-show="code==2" :src="loginImg" class="imgCode" />
            <div v-show="code==1" class="pad_20">
              <img src="../../assets/img/setting/wxupload-wait.png" class="loadWait" />
            </div>
            <div v-show="code==1" class="mar_b20">正在获取二维码,请耐心等待,等待时间大约</div>
            <div v-show="code==1" class="mar_t20 waitTime">{{ initTimer }}s</div>
            <div v-show="code==2" class="mar_b20">请扫描二维码，确认后将直接上传代码</div>
            <div v-show="code==3" class="mar_b20">
              <div class="mar_b20">扫描成功,等待上传代码,请稍后...</div>
              <img src="../../assets/img/setting/wxupload-wait.png" class="loadWait" />
              <div class="waitTime mar_t20">{{ updateTimes }}s</div>
            </div>
            <div v-show="code==4">上传代码成功，请到微信开发平台小程序后台预览，提交审核应用。</div>
            <div v-show="code==4">
              微信开发平台小程序后台
              <a href="https://mp.weixin.qq.com/" target="_blank">https://mp.weixin.qq.com/</a>
            </div>
            <img v-show="code==4" :src="previewImg" class="imgCode" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="二维码" :visible.sync="dialogVisible" :close-on-click-modal="false" width="30%">
        <div class="t_c">
          <img :src="codeImg" class="wid imgCode" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false" size="medium">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="mar_t20 ba_f pad_20 t_c" v-show="activeName!='2' && activeName!='4'">
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </div>
    <div class="mar_t20 ba_f pad_20 t_c" v-show="activeName=='4' && code==1">
      <el-button type="primary" @click="upload">确认并上传</el-button>
    </div>
  </div>
</template>
<script>
import {getConfig, getConfig2,getConfig3,postConfig, postConfig2,postConfig3,getPage, userList, getLoginCode, getLoginStatus, preview, getEdition} from '@/api/setup';
import {changeDate} from "@/utils";
import index from "@/api";

export default {
  created() {
    this.init();
    // this.getEdition();
  },
  data() {
    return {
      activeName: '1',
      form: {
        miniName: '',
        miniAppId: '',
        miniSecret: '',
      },
      form2: {

      },
      rules: {
        miniName: [{ required: true, message: '请输入小程序名称', trigger: 'blur' }],
        miniAppId: [{ required: true, message: '请输入AppId', trigger: 'blur' }],
        miniSecret: [{ required: true, message: '请输入appSecret', trigger: 'blur' }]
      },
      list: [],
      listLoading: true,
      selectRows: '',
      elementLoadingText: '正在加载...',
      page: {
        total: 0,
        size: 10,
        currentPage: 1
      },
      codeImg: '',
      dialogVisible: false,
      passw: 'password',
      icon: 'el-input__icon el-icon-view',
      data: '',
      form3: {
        version: '',
        describe: ''
      },
      plugin: [],
      shawCode: '1',
      initTimer: 60,
      times: 20,
      updateTimes: 60,
      code: 1,
      loginStatus: false,
      loginImg: '',
      previewImg: ''
    };
  },
  methods: {
    async getEdition() {
      const { data } = await getEdition();
      this.data = data;
    },
    async init() {
      if (this.activeName == '1') {
        this.bus.$emit('loading', true);
        this.formData();
      } else if (this.activeName == '2') {
        this.fetchData();
      }else if (this.activeName == '4') {
        this.uploadData();
      }
    },
    async handleClick() {
      if (this.activeName == '1') {
        this.formData();
      } else if (this.activeName == '2') {
        this.fetchData();
      }else if (this.activeName == '4') {
        this.uploadData();
      }
      // this.getEdition();
      this.code = 1;
    },
    async formData() {
      const { data } = await getConfig2({ ident: 'merchantConfig' });
      this.form2 = this.form;
      this.form = Object.assign(this.form2, data);
      this.bus.$emit('loading', false);
    },
    async fetchData() {
      this.listLoading = true;
      const { data ,count} = await userList({ page: this.page.currentPage });
      this.list = data;
      this.page.total = count;
      this.bus.$emit('loading', false);
      setTimeout(() => {
        this.listLoading = false;
      }, 100);
    },
    async uploadData() {
      this.shawCode = '1';
      const { data } = await getConfig3({ ident: 'shdUpdateConfig' });
      this.plugin = data.plugin ? data.plugin : [];
      this.form3 = Object.assign({}, data);
      this.bus.$emit('loading', false);
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.formData2();
    },
    downloadPage() {
      let backendPath = index.backendPath;
      return backendPath + 'channel/index/mini-down'
    },
    async onSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.form.ident = 'merchantConfig';
          this.form.identName = '商户端小程序配置';
          const { msg } = await postConfig2(this.form);
          this.$baseMessage(msg, 'success');
          this.init();
        } else {
          return false;
        }
      });
    },
    showPass() {
      if (this.passw == 'text') {
        this.passw = 'password';
        this.icon = 'el-input__icon el-icon-view';
      } else {
        this.passw = 'text';
        this.icon = 'el-input__icon el-icon-unlock';
      }
    },
    async upload() {
      if (this.form3.version == '') {
        this.$baseMessage('请填写版本号', 'warning');
        return;
      }
      if (this.form3.describe == '') {
        this.$baseMessage('请填写版本描述', 'warning');
        return;
      }
      // console.log(this.form3,this.plugin,this.checkList)
      // return
      const { data } = await postConfig3({ ident: 'shdUpdateConfig', identName: '上传商户端小程序', version: this.form3.version, describe: this.form3.describe, plugin: this.plugin });
      this.shawCode = '2';
      //登录码定时器
      if (this.code == '1') {
        this.initTimer = setInterval(() => {}, 5000);
        this.WxUpdate();
      } else {
        this.initTimer--;
      }
      this.loginTimer = setInterval(async () => {
        if (this.code == 2) {
          clearInterval(this.loginTimer);
          //登录状态定时器
          this.loginStatusTimer = setInterval(async () => {
            await this.GetLoginStatus({type:'shd'});
            if (this.code == 3) {
              clearInterval(this.loginStatusTimer);
              //预览定时器
              this.Preview();
              this.updateTimer = setInterval(async () => {
                if (this.code == 4) {
                  clearInterval(this.updateTimer);
                } else {
                  this.updateTimes--;
                  if (this.updateTimes === 0) {
                    clearInterval(this.updateTimer);
                    this.$baseMessage('上传失败请重试', 'error');
                    this.uploadData();
                  }
                }
              }, 1000);
            } else {
              this.updateTimes--;
              if (this.updateTimes === 0) {
                clearInterval(this.loginStatusTimer);
                this.$baseMessage('上传失败请重试', 'error');
                this.uploadData();
              }
            }
          }, 3000);
        } else {
          this.times--;
          if (this.times === 0) {
            clearInterval(this.loginTimer);
            this.$baseMessage('上传失败请重试', 'error');
            this.uploadData();
          }
        }
      }, 1200);
    },
    async WxUpdate() {
      const { msg, data } = await getLoginCode({type:'shd'});
      if (msg == '成功') {
        this.code = 2;
        this.loginImg = data;
      }
    },
    async GetLoginStatus() {
      const { msg, data } = await getLoginStatus({type:'shd'});
      if (msg == '成功') {
        this.code = 3;
      }
    },
    async Preview() {
      const { msg, data } = await preview({type:'shd'});
      var storeData = { id: this.id };
      if (msg == '成功') {
        this.code = 4;
        this.previewImg = data;
      } else {
        // this.$baseMessage(msg, "error");
        this.uploadData();
        this.$baseConfirm(
            msg,
            null,
            async () => {
              location.reload();
            },
            async () => {
              location.reload();
            }
        );
      }
    }
  }
};
</script>
<style>
.orderpop p {
  line-height: 24px;
}
.msgtext {
  text-indent: -70px;
  padding-left: 70px;
}
.imgCode {
  width: 200px;
  height: 200px;
}
.waitTime {
  font-size: 26px;
  margin-top: 10px;
  color: #2a75ed;
}
.loadWait {
  width: 32px;
  height: 32px;
}
.el-button.is-plain:focus,
.el-button.is-plain:hover {
  border-color: #155bd4;
  color: #fff;
}
/*步进器，进度条样式*/
.stepsLeft {
  height: 330px;
  padding-left: 30px;
  padding-top: 10px;
  padding-bottom: 20px;
}
.el-step.is-vertical .el-step__line {
  left: 12px;
  width: 1px;
}
.el-step__icon {
  width: 25px;
  height: 25px;
}
.el-step__title.is-finish,
.el-step__description.is-finish {
  color: #333;
}
.el-step__line-inner {
  border: none;
  border-left: 1px solid #67c23a;
}
.el-step__icon.is-text {
  border: 1px solid;
}
</style>
